﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Logic
{
	class MinesHost
	{
		int sizex, sizey;		
		int[,] field;
		bool[,] opened;
        List<int[]> zerosList = new List<int[]>();

		public int SizeX { get { return sizex; }}
		public int SizeY { get { return sizey; }}
		public readonly int[,] Directions = new[,] { { 0, -1 }, { -1, -1 }, { 1, -1 }, { 1, 1 }, { -1, 1 }, { 0, 1 }, { -1, 0 }, { 1, 0 } };

		public void DrawField()
		{			
			for(int y = 0; y < sizey; y++)
			{
				for (int x = 0; x < sizex; x++)
				{
					if (field[x, y] == -1)
					{
						Console.ForegroundColor = ConsoleColor.Red;
						Console.Write("* ");						
					}
					else
					{
						if (opened[x, y])
							Console.ForegroundColor = ConsoleColor.Green;
						Console.Write(field[x, y] + " ");

					}
					Console.ForegroundColor = ConsoleColor.Gray;
				}
				Console.WriteLine();
			}
		}

		

		public MinesHost(int sizex, int sizey, int minesCount)
		{
			this.sizex = sizex;
			this.sizey = sizey;
			field = new int[sizex, sizey];
			opened = new bool[sizex, sizey];			
			Random rand = new Random();
			for (int i = 0; i < minesCount; i++)
			{
				int x, y;
				do { x = rand.Next(sizex); y = rand.Next(sizey); } while (field[x, y] == -1);
				field[x, y] = -1;
			}

			for(int x = 0; x < sizex; x++)
				for (int y = 0; y < sizey; y++)
				{
					if (field[x, y] == -1) continue;
					int c = 0;
					for (int i = 0; i < Directions.GetLength(0); i++)
						if (IsMineHere(x + Directions[i, 0], y + Directions[i, 1])) c++;

					field[x, y] = c;
                    if (c == 0) zerosList.Add(new[] { x, y });
				}
		}

		public int Open(int x, int y)
		{
			opened[x, y] = true;
			return field[x, y];
		}

        public int[] CheatPleaseGiveMeZero()
        {
            Random rnd = new Random();
            return zerosList[rnd.Next(zerosList.Count)];
        }

		bool IsMineHere(int x, int y)
		{
			if (x < 0 || x >= sizex || y < 0 || y >= sizey) return false;
			return field[x, y] == -1;
		}
	}
}
